// pages/nfc/nfc.js
const app = getApp()
const logs = require('../logs/log_func.js')
import fnNfc from 'nfc_func.js' // nfc内容引入
const dithering = require('../index/dithering.js')

function inArray(arr, key, val, key2 = "", val2 = "") {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val && arr[i][key2] === val2) {
      return i;
    }
  }
  return -1;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    width: app.globalData.epd_width, //宽度
    height: app.globalData.epd_height, //高度
    epd_image_width:350,
    upload_percent: 0,
    check_num: 0,
    // image_data: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {



    const pages = getCurrentPages();
    const prePage = pages[pages.length - 2]; //上一个页面

    this.setData({
      epd_image_width:prePage.__data__.config.epd_image_width,
      width: app.globalData.epd_width,
      height: app.globalData.epd_height   

    })
    console.log(this.data.height, this.data.width)
    this.nfcRead()
  },


  init(res) {
    console.log(res)

    const canvas = res[0].node
    const pages = getCurrentPages();
    const prePage = pages[pages.length - 2]; //上一个页面
    const canvas2 = prePage.__data__.canvas;

    const ctx2 = canvas2.getContext("2d");
    const imageData_temp = ctx2.getImageData(0, 0, canvas2.width, canvas2.height);
    console.log(res[0].width, res[0].height)
    const ctx = canvas.getContext('2d')
    let canvas_scale = this.data.epd_image_width / this.data.width

    canvas.width = res[0].width/canvas_scale // 获取宽
    canvas.height = res[0].height/canvas_scale // 获取高

    console.log(canvas.width, canvas.height)
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    var mode //test     
    mode = prePage.__data__.config.epd.color == 2 ? prePage.__data__.dithering_select.objectArray[prePage.__data__.config.page_image.dithering_index].value2 : prePage.__data__.dithering_select.objectArray[prePage.__data__.config.page_image.dithering_index].value3
    console.log(mode)
    const imageData_temp2 = dithering.convert_dithering(imageData_temp, mode, prePage.__data__.config.page_image.threshold_set)
    ctx.putImageData(imageData_temp2, 0, 0)
  
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    const nfc = wx.getNFCAdapter()
    nfc.stopDiscovery({
      complete(res) {
        console.log(res)
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    //模拟加载
    setTimeout(function () {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 500)
    const pages = getCurrentPages();
    // console.log(pages)
    // const currPage = pages[pages.length - 1];//当前页面
    const url = '/' + pages[pages.length - 1].route; //当前页面
    // console.log(url)
    wx.redirectTo({
      url: url,
      success: function (res) {
        console.log('页面刷新成功');
      },
      fail: function (res) {
        console.log('页面刷新失败');
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  nfc_image_pre(type) {

    console.log(type)
    const pages = getCurrentPages();
    const prePage = pages[pages.length - 2]; //上一个页面
    const canvas = prePage.__data__.canvas

    const image_data = dithering.canvas2bytes(canvas, type, (prePage.__data__.config.epd.rotation + prePage.__data__.config.epd.rotationSet) & 3)
   
    return image_data
  },
  /**
   * @brief 获取数据的校验和
   *
   * @return UINT8
   */
  checksum(oldArray) {
    let sum = 0;

    oldArray.forEach((item) => {
      sum += item;
    })
    sum &= 0xFF;
    return sum;
  },
  sendbuffer(type, data = [], color_type = null, start_index = 0, buffer_length = null) {

    let nfc_send_cmd = new Uint8Array(3)
    let nfc_send_data_lenghth = 0
    let nfc_send_data
    nfc_send_cmd[0] = 0x02
    nfc_send_cmd[1] = 0xAA
    nfc_send_cmd[2] = 0x02
    // console.log(nfc_send_cmd)    

    const pages = getCurrentPages();
    const prePage = pages[pages.length - 2]; //上一个页面
    const epd = prePage.__data__.config.epd
    const mode = prePage.__data__.config.epd.color == 2 ? prePage.__data__.dithering_select.objectArray[prePage.__data__.config.page_image.dithering_index].value2 : prePage.__data__.dithering_select.objectArray[prePage.__data__.config.page_image.dithering_index].value3
    // console.log(mode)
    if (type == 'inti') {
      nfc_send_data_lenghth = 6
      nfc_send_data = new Uint8Array(nfc_send_data_lenghth)
      nfc_send_data[0] = 0X20 //cmd
      nfc_send_data[1] = (epd.width >> 8) & 0xFF //width
      nfc_send_data[2] = epd.width & 0xFF //width
      nfc_send_data[3] = (epd.height >> 8) & 0xFF //height
      nfc_send_data[4] = epd.height & 0xFF //height
      nfc_send_data[5] = epd.color & 0xFF //color
      // this.data.check_num=0
    } else if (type == 'end') {
      nfc_send_data_lenghth = 5
      nfc_send_data = new Uint8Array(nfc_send_data_lenghth)
      nfc_send_data[0] = 0X2F //cmd
      let totalsize = epd.height * epd.width / 8 * (epd.color == 2 ? 1 : 2)
      nfc_send_data[1] = (totalsize >> 16) & 0xFF //totalsize
      nfc_send_data[2] = (totalsize >> 8) & 0xFF //totalsize
      nfc_send_data[3] = totalsize & 0xFF //totalsize
      nfc_send_data[4] = this.data.check_num //check_num
      console.log('check_num', this.data.check_num)
    } else if (type == 'data') {
      nfc_send_data_lenghth = 4 + buffer_length
      nfc_send_data = new Uint8Array(4)
      nfc_send_data[0] = 0X2A //cmd

      let color_code
      if (color_type == 'black') {
        color_code = 0
      } else if (color_type == 'red') {
        color_code = 1
      } else if (color_type == 'rle-black') {
        color_code = 0XA0
      } else if (color_type == 'rle-red') {
        color_code = 0XA1
      }
      nfc_send_data[1] = color_code & 0xFF //color_type
      nfc_send_data[2] = (buffer_length >> 8) & 0xFF //buffer_length
      nfc_send_data[3] = buffer_length & 0xFF //buffer_length
      let databuffer = data.slice(start_index, start_index + buffer_length)
      // console.log(databuffer)
      // nfc_send_data=nfc_send_data.buffer
      nfc_send_data = [...nfc_send_data, ...databuffer]
      // console.log(nfc_send_data)
      // nfc_send_data=nfc_send_data.concat(databuffer)
      // console.log(nfc_send_data)
    } else if (type == 'grey_inti') {
      nfc_send_data_lenghth = 6
      nfc_send_data = new Uint8Array(nfc_send_data_lenghth)
      nfc_send_data[0] = 0X22 //cmd
      nfc_send_data[1] = (epd.width >> 8) & 0xFF //width
      nfc_send_data[2] = epd.width & 0xFF //width
      nfc_send_data[3] = (epd.height >> 8) & 0xFF //height
      nfc_send_data[4] = epd.height & 0xFF //height
      let greyscale
      if (mode == 'grey_4bit')
        greyscale = 4
      else if (mode == 'grey_16bit')
        greyscale = 16
      nfc_send_data[5] = greyscale & 0xFF //greyscale
      // this.data.check_num=0
    } else if (type == 'grey_end') {
      nfc_send_data_lenghth = 5
      nfc_send_data = new Uint8Array(nfc_send_data_lenghth)
      nfc_send_data[0] = 0X24 //cmd

      let piex_data_size
      if (mode == 'grey_4bit')
        piex_data_size = 2
      else if (mode == 'grey_16bit')
        piex_data_size = 4

      let totalsize = epd.height * epd.width / 8 * piex_data_size
      nfc_send_data[1] = (totalsize >> 16) & 0xFF //totalsize
      nfc_send_data[2] = (totalsize >> 8) & 0xFF //totalsize
      nfc_send_data[3] = totalsize & 0xFF //totalsize
      nfc_send_data[4] = this.data.check_num //check_num
      console.log('check_num', this.data.check_num)
    } else if (type == 'grey_data') {
      nfc_send_data_lenghth = 4 + buffer_length
      nfc_send_data = new Uint8Array(4)
      nfc_send_data[0] = 0X23 //cmd

      let color_code = 0
      if (color_type == 'rle-black') {
        color_code = 0XA0
      }

      nfc_send_data[1] = color_code & 0xFF //color_type
      nfc_send_data[2] = (buffer_length >> 8) & 0xFF //buffer_length
      nfc_send_data[3] = buffer_length & 0xFF //buffer_length
      let databuffer = data.slice(start_index, start_index + buffer_length)

      nfc_send_data = [...nfc_send_data, ...databuffer]

    }
    else if (type == 'grey_bwr_inti') {
      nfc_send_data_lenghth = 6
      nfc_send_data = new Uint8Array(nfc_send_data_lenghth)
      nfc_send_data[0] = 0X22 //cmd
      nfc_send_data[1] = (epd.width >> 8) & 0xFF //width
      nfc_send_data[2] = epd.width & 0xFF //width
      nfc_send_data[3] = (epd.height >> 8) & 0xFF //height
      nfc_send_data[4] = epd.height & 0xFF //height
      let greyscale
      if (mode == 'grey_bwr_4bit')
        greyscale = 4
      else if (mode == 'grey_bwr_8bit')
        greyscale = 8
      nfc_send_data[5] = greyscale & 0xFF //greyscale
      // this.data.check_num=0
    } else if (type == 'grey_bwr_end') {
      nfc_send_data_lenghth = 5
      nfc_send_data = new Uint8Array(nfc_send_data_lenghth)
      nfc_send_data[0] = 0X24 //cmd

      let piex_data_size
      if (mode == 'grey_bwr_4bit')
        piex_data_size = 3
      else if (mode == 'grey_bwr_8bit')
        piex_data_size = 4

      let totalsize = epd.height * epd.width / 8 * piex_data_size
      nfc_send_data[1] = (totalsize >> 16) & 0xFF //totalsize
      nfc_send_data[2] = (totalsize >> 8) & 0xFF //totalsize
      nfc_send_data[3] = totalsize & 0xFF //totalsize
      nfc_send_data[4] = this.data.check_num //check_num
      console.log('check_num', this.data.check_num)
    } else if (type == 'grey_bwr_data') {
      nfc_send_data_lenghth = 4 + buffer_length
      nfc_send_data = new Uint8Array(4)
      nfc_send_data[0] = 0X23 //cmd

      let color_code = 0
      if (color_type == 'rle-black') {
        color_code = 0XA0
      }
      nfc_send_data[1] = color_code & 0xFF //color_type
      nfc_send_data[2] = (buffer_length >> 8) & 0xFF //buffer_length
      nfc_send_data[3] = buffer_length & 0xFF //buffer_length
      let databuffer = data.slice(start_index, start_index + buffer_length)
      nfc_send_data = [...nfc_send_data, ...databuffer]

    }

    let nfc_send_buffer = [...nfc_send_cmd, ...[(nfc_send_data_lenghth - 1)], ...nfc_send_data]
    nfc_send_buffer = new Uint8Array(nfc_send_buffer);
    nfc_send_buffer = nfc_send_buffer.buffer

    return nfc_send_buffer
  },

  nfcRead() {

    wx.createSelectorQuery()
      .select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec(this.init.bind(this))
    const nfc = wx.getNFCAdapter()
    this.nfc = fnNfc
    var _this = this

    function discoverHandler(res) {
      console.log('discoverHandler', res) // 发现者 
      const data = new Uint8Array(res.id)
      let str = ""
      data.forEach(e => {
        let item = e.toString(16)
        if (item.length == 1) {
          item = '0' + item
        }
        item = item.toUpperCase()

        str += item
      })
      _this.setData({
        newCardCode: str
      })
      console.log(str)
   
      const nfcv = nfc.getNfcV()
      console.log(nfcv)
      nfcv.connect({
        fail(res) {
          console.log(res)
        },
        success(res) {
          console.log(res)
          nfcv.getMaxTransceiveLength({
            complete(res) {
              console.log(res)
            }
          })
          setTimeout(() => {
          const pages = getCurrentPages();
          const prePage = pages[pages.length - 2]; //上一个页面
          const mode = prePage.__data__.config.epd.color == 2 ? prePage.__data__.dithering_select.objectArray[prePage.__data__.config.page_image.dithering_index].value2 : prePage.__data__.dithering_select.objectArray[prePage.__data__.config.page_image.dithering_index].value3
          const epd = prePage.__data__.config.epd

          let image_black_data_temp = []
          let image_red_data_temp = []
          let image_black_data = []
          let image_red_data = []
          let compress_black_type = ''
          let compress_red_type = ''

          if (mode.startsWith('grey_bwr')) {
            image_black_data_temp = _this.nfc_image_pre(mode)
          } else if (mode.startsWith('grey')) {
            image_black_data_temp = _this.nfc_image_pre(mode)
          } else if (mode.startsWith('bwr')) {
            image_black_data_temp = _this.nfc_image_pre('bw')
            image_red_data_temp = _this.nfc_image_pre('bwr')
          } else {
            image_black_data_temp = _this.nfc_image_pre('bw')
            if (prePage.__data__.config.epd.color == 3) {
              image_red_data_temp = new Array(prePage.__data__.config.epd.height * prePage.__data__.config.epd.width / 8).fill(0);
            }
          }
          let check_num_balck = _this.checksum(image_black_data_temp)
          let check_num_red = mode.startsWith('bwr') ? _this.checksum(image_red_data_temp) : 0
          console.log(check_num_balck, check_num_red)
          _this.setData({
            check_num: (check_num_balck + check_num_red) & 0xFF
          })

          if (1) //black
          {
            const image_data_rle = dithering.run_length_encoding2(image_black_data_temp)
            console.log("压缩前,压缩后,压缩比例:%d,%d,%d%%.........", image_black_data_temp.length, image_data_rle.length, Math.round(image_data_rle.length / image_black_data_temp.length * 100, 2))
            logs.printLog(`压缩前,压缩后,压缩比例: ${image_black_data_temp.length}, ${image_data_rle.length}, ${Math.round(image_data_rle.length / image_black_data_temp.length * 100, 2)}%`)
            image_black_data = image_data_rle
            compress_black_type = 'rle-black'
          }

          if (mode.startsWith('bwr') || (prePage.__data__.config.epd.color == 3) && (!mode.startsWith('grey_bwr'))) { //red
            const image_data_rle = dithering.run_length_encoding2(image_red_data_temp)
            console.log("压缩前,压缩后,压缩比例:%d,%d,%d%%.........", image_red_data_temp.length, image_data_rle.length, Math.round(image_data_rle.length / image_red_data_temp.length * 100, 2))
            logs.printLog(`压缩前,压缩后,压缩比例: ${image_red_data_temp.length}, ${image_data_rle.length}, ${Math.round(image_data_rle.length / image_red_data_temp.length * 100, 2)}%`)
            image_red_data = image_data_rle
            compress_red_type = 'rle-red'
          }


          let index = 0
          let index2 = 0
          _this.setData({
            upload_percent: 0
          })
          let nfc_send_length = 245 //<=245
          let length
          let buffer
          if (mode.startsWith('grey_bwr')) {
            buffer = _this.sendbuffer('grey_bwr_inti')
          } else if (mode.startsWith('grey')) {
            buffer = _this.sendbuffer('grey_inti')
          } else {
            buffer = _this.sendbuffer('inti')
          }
          console.log(buffer)
          nfcv.transceive({
            data: buffer,
            success(res) {

              let inti_time_interval = 1 //ms
              setTimeout(() => {

                //data_black
                for (let j = 0; j < image_black_data.length; j += length) {
                  length = Math.min(nfc_send_length, image_black_data.length - index)
                  let length2 = length
                  if (mode.startsWith('grey_bwr')) {
                    buffer = _this.sendbuffer('grey_bwr_data', image_black_data, compress_black_type, index, length, 0)
                  } else if (mode.startsWith('grey')) {
                    buffer = _this.sendbuffer('grey_data', image_black_data, compress_black_type, index, length, 0)
                  } else {
                    buffer = _this.sendbuffer('data', image_black_data, compress_black_type, index, length, 0)
                  }
                  console.log(buffer)
                  index += length

                  nfcv.transceive({
                    data: buffer,
                    success(res) {
                      index2 += length2

                      let upload_percent = Math.round(index2 / (image_black_data.length + image_red_data.length ) * 100)

                      _this.setData({
                        upload_percent
                      })
                      console.log(upload_percent + '%')
                      console.log(index2)
                      console.log(res)
                      let data_black_time_interval = 1//200 //128ms 2888

                      if (index2 == image_black_data.length) //black finished ,to red
                      {

                        if (mode.startsWith('bwr') || (prePage.__data__.config.epd.color == 3) && (!mode.startsWith('grey_bwr'))) { //red_data
                          setTimeout(() => {
                            index = 0
                            for (let j = 0; j < image_red_data.length; j += length) {
                              length = Math.min(nfc_send_length, image_red_data.length - index)
                              let length2 = length

                              buffer = _this.sendbuffer('data', image_red_data, compress_red_type, index, length, 0)
                              console.log(buffer)
                              index += length

                              nfcv.transceive({
                                data: buffer,
                                success(res) {
                                  index2 += length2
                                  let upload_percent = Math.round(index2 / (image_black_data.length + image_red_data.length ) * 100)
                                  _this.setData({
                                    upload_percent
                                  })
                                  console.log(upload_percent + '%')
                                  console.log(index2)
                                  console.log(res)
                                  if (index2 == image_black_data.length + image_red_data.length)//red finished ,to end
                                  {
                                    setTimeout(() => {
                                      {
                                        buffer = _this.sendbuffer('end')
                                      }
                                      nfcv.transceive({
                                        data: buffer,
                                        complete(res) {
                                          console.log(res)
                                        }
                                      })
                                    }, 1);
                                  }
                                },
                                fail(res) {
                                  console.log(res)
                                }
                              })

                            }

                          }, data_black_time_interval);
                        }
                        else {//NOT BWR
                          let end_time_interval = epd.color == 3 ? data_black_time_interval : 1

                          setTimeout(() => {
                            if (mode.startsWith('grey_bwr')) {
                              buffer = _this.sendbuffer('grey_bwr_end')
                            }
                            else if (mode.startsWith('grey')) {
                              buffer = _this.sendbuffer('grey_end')
                            } else {
                              buffer = _this.sendbuffer('end')
                            }
                            nfcv.transceive({
                              data: buffer,
                              complete(res) {
                                console.log(res)
                              }
                            })
                          }, end_time_interval);
                        }
                      }
                    },
                    fail(res) {
                      console.log(res)
                    }
                  })
                }
              }, inti_time_interval);
            },
            fail(res) {
              console.log(res)
            }
          })
        }, 30);
        }
      })
    }

    nfc.startDiscovery({
      success(res) {
        console.log(res)
        wx.showToast({
          title: 'NFC读取功能已开启！',
          icon: 'none'
        })
        nfc.onDiscovered(discoverHandler)
      },
      fail(err) {
        console.log('failed to discover:', err)
        if (!err.errCode) {
          wx.showToast({
            title: '请检查NFC功能是否正常!',
            icon: 'none'
          })
          return
        }
        switch (err.errCode) {
          case 13000:
            wx.showToast({
              title: '设备不支持NFC!',
              icon: 'none'
            })
            break;
          case 13001:
            wx.showToast({
              title: '系统NFC开关未打开!',
              icon: 'none'
            })
            break;
          case 13019:
            wx.showToast({
              title: '用户未授权!',
              icon: 'none'
            })
            break;
          case 13010:
            wx.showToast({
              title: '未知错误!',
              icon: 'none'
            })
            break;
        }
      }
    })
  },

  bindBack() {
    wx.navigateBack({
      delta: -1
    })
  },

})